package com.tarena.lbs.basic.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.tarena.lbs.basic.dao.repository.AreaRepository;
import com.tarena.lbs.basic.pojo.po.AreaPO;
import com.tarena.lbs.basic.pojo.vo.AreaVO;
import com.tarena.lbs.basic.service.AreaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AreaServiceImpl implements AreaService {
    @Autowired
    private AreaRepository areaRepository;
    @Override
    public List<AreaVO> queryProvinces() {
        List<AreaVO> list = null;
        List<AreaPO> poList = areaRepository.queryProvinces();
        if(CollectionUtils.isNotEmpty(poList)){
            list = new ArrayList<>();
            for (AreaPO po : poList) {
                AreaVO vo = new AreaVO();
                BeanUtils.copyProperties(po,vo);
                list.add(vo);
            }
        }
        return list;
    }

    @Override
    public List<AreaVO> queryChildren(Integer parentId) {
        log.info("查询子级地区，入参:{}",parentId);
        List<AreaVO> list = null;
        List<AreaPO> poList = areaRepository.queryChildren(parentId);
        if(CollectionUtils.isNotEmpty(poList)){
            list = new ArrayList<>();
            for (AreaPO po : poList) {
                AreaVO vo = new AreaVO();
                BeanUtils.copyProperties(po,vo);
                list.add(vo);
            }
        }
        return list;
    }

    /*
    * 查询地市树
    * */
    @Override
    public List<AreaVO> getAreaTree() {
        List<AreaPO> allAreas=areaRepository.queryAllAreas();
        if (CollectionUtils.isEmpty(allAreas)){
            return new ArrayList<>();
        }
        List<AreaVO> areaVOs=allAreas.stream().map(po -> {
            AreaVO vo = new AreaVO();
            BeanUtils.copyProperties(po,vo);
            return vo;
        }).collect(Collectors.toList());
        return buildAreaTree(areaVOs,0L);
    }

    private List<AreaVO> buildAreaTree(List<AreaVO> areas, Long parentId) {
        // 筛选出所有父ID等于指定parentId的地区，并为每个地区设置其子地区
        return areas.stream()
                .filter(area -> parentId.equals(area.getParentId()))  // 筛选当前层级的地区
                .peek(area -> {
                    // 递归查找并设置子地区
                    List<AreaVO> children = buildAreaTree(areas, area.getId());
                    area.setChildren(children);
                })
                .collect(Collectors.toList());
    }

}
